import isEmpty from 'loadsh/isEmpty'
import {
  GetEvectionInfo,
  GetInfoPicture,
  GetPreviewImage,
  PostDeleteData,
  PostEvectionInfo,
  PostInfoPicture,
  GetProjectArchivingInfo,
} from '/constData/requestFun/_httpRequest';
import {
  EvectionDeleteData,
  GetEvection,
  GetEvectionById,
  GetProjectManagement,
  PostEvection
} from '/constData/requestFun/_teseRequest';
import {
  POLICIES
} from '/constData/_';
import compact from 'loadsh/compact'
import {
  CORPID,
  SPACEID
} from '/constData/requestFun/_globalData';
Page({
  data: {
    approve: [],
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    defaultValue: '上午',
    daylist: ['上午', '下午'],
    evectioninfo: {
      CorpId: '', //申请人名字
      TravelType: '',
      TypeDependent: '', //类型相关
      PlaceDeparture: '', //出发地
      Destination: '', //目的地
      Vehicle: '', //交通工具
      Colleague: '', //同行人名字
      StartDate: new Date(), //开始时间
      StartDateSuffix: '上午', //上午
      EndDate: new Date(), //结束时间
      EndDateSuffix: '上午', //上午
      SumTime: '0.5', //时长 
      BusinessTrip: '', //出差事由
      Annex: '[]', //附件
      AddJourney: [],
    },
    displaydata: [],
    ReceiveData: [],
    list: ['请点击选择出差类型', '项目出差', '业务出差', '常规出差'],
    position: '',
    basicVisible: false,
    animation: true,
    closeVisible: false,
    ProjectData: [],
    ProjectDisplayData: [],
  },
  AddJourney() {
    // 创建一个新的旅程对象  
    const newJourney = {
      Vehicle: '飞机', // 假设默认交通工具为飞机  
      PlaceDeparture: '北京', // 出发地  
      Destination: '上海', // 目的地  
      StartDate: new Date(), // 当前时间作为开始时间  
      EndDate: new Date(new Date().getTime() + 86400000), // 假设结束时间为一天后  
      StartDateSuffix: '上午', //上午
      EndDateSuffix: '上午', //上午
      SumTime: '1', // 时长，这里简单设为1天  
      // 其他字段可以根据需要添加默认值或留空  
    };
    const addJourneys = this.data.evectioninfo.AddJourney.concat([newJourney]);
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: addJourneys
      }
    })
    console.log('SSS',addJourneys);
  },
  DeleteJourney(e){
    // 从事件对象中获取索引  
    const index = e.currentTarget.dataset.index;  
    // 移除对应的旅程  
    const addJourneys = this.data.evectioninfo.AddJourney.filter((_, i) => i !== index);  
  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: addJourneys
      }
    })
  },
  VehicleChange(value, e){
    const AddJourney = this.data.evectioninfo.AddJourney; // 获取当前的试验列表  
    AddJourney[e.currentTarget.dataset.index].Vehicle = value; // 索引从1开始，但数组索引从0开始，所以需要减1  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney // 设置更新后的试验列表  
      }
    });
    // console.log('eee1',this.data.evectioninfo.AddJourney);
  },
  PlaceDepartureChange(value, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].PlaceDeparture = value;  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  DestinationChange(value, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].Destination = value;  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  
  StartDateOk(value, format, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].StartDate = value;
    AddJourney[e.currentTarget.dataset.index].SumTime = (DayCompute(value, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDateSuffix, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDate,this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDateSuffix)).toFixed(1),  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  StartDateSuffixOk(value, format, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].StartDateSuffix = value; 
    AddJourney[e.currentTarget.dataset.index].SumTime = (DayCompute(this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDate, value, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDate, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDateSuffix)).toFixed(1); 
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  EndDateOk(value, format, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].EndDate = value;
    AddJourney[e.currentTarget.dataset.index].SumTime = (DayCompute(this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDate, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDateSuffix, value, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDateSuffix)).toFixed(1),  
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  EndDateSuffixOk(value, format, e){
    const AddJourney = this.data.evectioninfo.AddJourney; 
    AddJourney[e.currentTarget.dataset.index].EndDateSuffix = value;  
    AddJourney[e.currentTarget.dataset.index].SumTime = (DayCompute(this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDate, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].StartDateSuffix, this.data.evectioninfo.AddJourney[e.currentTarget.dataset.index].EndDate, value)).toFixed(1),
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        AddJourney: AddJourney  
      }
    });
  },
  selectorProject(e) {
    const data = e.target.dataset.data
    this.setData({
      ProjectDisplayData: [...this.data.ProjectDisplayData, data]
    })
  },
  PickerhandleOk(value) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        StartDateSuffix: value,
        SumTime: (DayCompute(this.data.evectioninfo.StartDate, value, this.data.evectioninfo.EndDate, this.data.evectioninfo.EndDateSuffix)).toFixed(1),
      }
    })
  },
  PickerEndOk(value) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        EndDateSuffix: value,
        SumTime: (DayCompute(this.data.evectioninfo.StartDate, this.data.evectioninfo.StartDateSuffix, this.data.evectioninfo.EndDate, value)).toFixed(1),
      }
    })
  },
  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({
      closeVisible: true
    });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetProjectManagement((res) => {
          this.setData({
            ProjectData: res.data
          })
        })
        this.setData({
          evectioninfo: {
            ...this.data.evectioninfo,
            CorpId: storage.data.result.userid
          }
        })
      }
    })
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    EvectionDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  handleOk1(date, format, e) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        StartDate: date,
        EndDate: date,
      },
      min: date
    })
  },
  handleOk2(date) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        EndDate: date,
        SumTime: (DayCompute(this.data.evectioninfo.StartDate, this.data.evectioninfo.StartDateSuffix, date, this.data.evectioninfo.EndDateSuffix)).toFixed(1),
      },
      approve: POLICIES.LEAVE_POLICIES(((date - this.data.evectioninfo.StartDate) / 1000 / 60 / 60 / 24).toFixed(2))
    })
  },
  OnType(value) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        TravelType: value
      }
    })
  },
  onTypeDependentChange(value) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        TypeDependent: value
      }
    })


  },
  onDepartureChange(e) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        PlaceDeparture: e
      }
    })
  },
  onDestinationChange(e) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        Destination: e
      }
    })
  },
  onVehicleChange(e) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        Vehicle: e
      }
    })
  },
  onDescriptionChange(e) {
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        BusinessTrip: e
      }
    })
  },

  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetEvection((res) => {
          // console.log('res',res);
          const cacheData = res.data.map(it => {
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
              it.item1['displayAddJourney'] = JSON.parse(it.item1.addJourney)
              return it
            }
          })
          this.setData({
            evectioninfo: {
              ...this.data.evectioninfo,
              CorpId: storage.data.result.userid
            },
            ReceiveData: compact(cacheData).reverse()
          })
          console.log('数据', this.data.ReceiveData);
        })
      }
    })
  },
  // 上传数据
  onSubmit(e) {
    //上传时，将AddJourney数组转换为字符串
    this.setData({  
      evectioninfo: {  
        ...this.data.evectioninfo,  
        AddJourney: JSON.stringify(this.data.evectioninfo.AddJourney)  
      }  
    });  
    // console.log('提交数据', JSON.stringify(this.data.evectioninfo));
    PostEvection(JSON.stringify(this.data.evectioninfo),
      (res) => {
        my.alert({
          title: '提交成功',
        });
        GetEvectionById(res.data, (res) => {
          this.setData({
            ReceiveData: compact([...this.data.ReceiveData, res.data].map(it => {
              if (it.item1.corpId === this.data.evectioninfo.CorpId) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
                it.item1['displayAddJourney'] = JSON.parse(it.item1.addJourney)
                return it
              }
            })).reverse()
          })
        })
        this.setData({
          evectioninfo: {
            ...this.data.evectioninfo,
            TravelType: '',
            TypeDependent: '', //类型相关
            PlaceDeparture: '', //出发地
            Destination: '', //目的地
            Vehicle: '', //交通工具
            Colleague: '', //同行人名字
            StartDate: new Date(), //开始时间
            StartDateSuffix: '上午', //上午
            EndDate: new Date(), //结束时间
            EndDateSuffix: '上午', //上午
            SumTime: '0.5', //时长 
            BusinessTrip: '', //出差事由
            Annex: '[]', //附件
            AddJourney: []
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },
  //上传图片
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcAnnex = this.data.evectioninfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))

        this.setData({
          displaydata: imageAnnex,
          evectioninfo: {
            ...this.data.evectioninfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => {},
      complete: () => {},
    });
  },
  /**
   * 预览图片
   */
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },

  // 选择同行人
  Members() {
    my.complexChoose({
      title: "测试标题", //标题
      multiple: true, //是否多选
      limitTips: "超出了", //超过限定人数返回提示
      maxUsers: 1000, //最大可选人数
      responseUserOnly: true, //返回人，或者返回人和部门
      success: (res) => {
        console.log('res', res);
        // this.setData({
        //   evectioninfo: {
        //     ...this.data.evectioninfo,
        //     Colleague: [],
        //   }
        // })
        let TempColleague = ''
        for (let index = 0; index < res.users.length; index++) {
          TempColleague += res.users[index].name + ' '
        }
        this.setData({
          evectioninfo: {
            ...this.data.evectioninfo,
            Colleague: TempColleague,
            // Colleague: [...this.data.evectioninfo.Colleague, res.users[index].name],
          }
        })

      },
      fail: function (err) {}
    })
  },
  Del(e) {
    const n = e.target.dataset.name
    console.log('e', n);
    this.setData({
      evectioninfo: {
        ...this.data.evectioninfo,
        Colleague: ''
        // Colleague: this.data.evectioninfo.Colleague.filter((name) => {
        //   return !name.includes(n)
        // })
      }
    })
  },

  //图片下载函数
  DownImg(e) {
    const imgNames = e.currentTarget.dataset.annex.split(',');
    if (isEmpty(e.currentTarget.dataset.annex)) {
      my.alert({
        content: '无附件图片！'
      })
    } else {
      Promise.all(imgNames.map(imgName =>
        new Promise((resolve) => {
          GetInfoPicture(imgName, (res) => {
            resolve(res.filePath)
          })
        })
      )).then(res => {
        GetPreviewImage(res)
      })
    }
  },
});

function DayCompute(StartDate, StartDateSuffix, EndDate, EndDateSuffix) {
  if (StartDateSuffix === EndDateSuffix) {
    return Math.ceil(((EndDate - StartDate) / 1000 / 60 / 60 / 24)) + 0.5;
  } else {
    if (StartDateSuffix === '上午' && EndDateSuffix === '下午') {
      return Math.ceil(((EndDate - StartDate) / 1000 / 60 / 60 / 24)) + 1;
    }
    if (StartDateSuffix === '下午' && EndDateSuffix === '上午') {
      return Math.ceil(((EndDate - StartDate) / 1000 / 60 / 60 / 24));
    }
  }
}